package com.piggy.common.core.aspectj;

import com.piggy.common.core.annotation.MakeAdmin;
import com.piggy.common.core.constant.UserConstants;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 数据过滤处理
 *
 * @author Lion Li
 */
@Aspect
@Component
public class MakeAdminAspect {

	// 配置织入点
	@Pointcut("@annotation(com.piggy.common.core.annotation.MakeAdmin)")
	public void dataScopePointCut() {
	}

	@Before("dataScopePointCut()")
	public void doBefore(JoinPoint point) throws Throwable {
		handleDataScope(point);
	}
	protected void handleDataScope(final JoinPoint joinPoint) {
		// 获得注解
		MakeAdmin userAnnotation = getAnnotation(joinPoint);

		if (userAnnotation == null) {
			return;
		}

		//todo 获取数据库用户待定
//		LoginUser loginUser = new LoginUser().setUser(new SysUser().setUserName(UserConstants.ADMIN_NAME).setUserId(UserConstants.ADMIN_ID));
//		UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
//		SecurityContextHolder.getContext().setAuthentication(authenticationToken);
	}


	/**
	 * 是否存在注解，如果存在就获取
	 */
	private MakeAdmin getAnnotation(JoinPoint joinPoint) {
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();

		if (method != null) {
			return method.getAnnotation(MakeAdmin.class);
		}
		return null;
	}

}
